package com.authine.cloudpivot.ext.controller.RP;

        import cn.hutool.core.lang.Assert;
        import com.authine.cloudpivot.engine.api.model.organization.UserModel;
        import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
        import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
        import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
        import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
        import com.authine.cloudpivot.ext.Utils.CustomSchemaCode;
        import com.authine.cloudpivot.ext.service.CloudSqlService;
        import com.authine.cloudpivot.web.api.config.EducationEnum;
        import com.authine.cloudpivot.web.api.config.FirstEducationEnum;
        import com.authine.cloudpivot.web.api.controller.base.BaseController;
        import lombok.extern.slf4j.Slf4j;
        import org.apache.commons.collections4.MapUtils;
        import org.apache.commons.lang3.StringUtils;
        import org.apache.commons.lang3.time.DateFormatUtils;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.web.bind.annotation.RequestMapping;
        import org.springframework.web.bind.annotation.RestController;

        import java.time.LocalDateTime;
        import java.time.format.DateTimeFormatter;
        import java.util.*;

/**
 *  问题标准
 **/
@RestController
@RequestMapping("/public/RPStandard")
@Slf4j
public class RPStandard extends BaseController {


    @Autowired
    CloudSqlService sqlService;

    /**
     *  错失标准  审批流完成后 数据写到-错失标准 基础表 基础
     */
    @RequestMapping("finish")
    public void finish(String bizId){
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.RPStandardAdd, bizId);

        List<Map<String,Object>> list = (List<Map<String, Object>>) bizObject.get("Sheet1673317905994");

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        //获取审批人

        String approval = getFileBaseInfoWorkFlowApproval(bizObject);

        for (Map<String, Object> map : list) {

            try {
                //获取数据
                Map<String, Object> data = fileInfoBaseMap(map, now, approval);
                //判断是否已存在
                String id = existsBizObject(map);
                if (StringUtils.isNotEmpty(id)) {
                    data.put("id", id);
                }

                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.RPStandardBase, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                log.info("基础表-人员信息基础作成功 ");
                //调用存储过程
                callProcess(id);

            } catch (Exception e) {
                String funNumber = (String) map.get("txtfuncode");
                String rpstandardNumber = (String) map.get("rpstandardcode");

                log.info("基础表-人员信息基础操作失败 funNumber={},rpstandardNumber={}", funNumber,rpstandardNumber);
                log.info(e.getMessage(), e);
            }

        }
    }
    @RequestMapping("toVoid")
    public void toVoid(String bizId){
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.RPStandardVoid, bizId);
        List<Map<String,Object>> list = (List<Map<String, Object>>) bizObject.get("SheetRPStandardVoid");

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        //获取审批人

        String approval = getFileBaseInfoWorkFlowApproval(bizObject);

        for (Map<String, Object> map : list) {


            try {
                //获取数据
                Map<String, Object> data = fileInfoBaseMap(map, now, approval);
                //判断是否已存在
                String id = existsBizObject(data);
                if (StringUtils.isNotEmpty(id)) {
                    data.put("id", id);
                }

                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.RPStandardBase, data, false);
                model.setSequenceStatus(SequenceStatus.CANCELED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                log.info("基础表-人员信息基础作废操作成功 ");
                //调用存储过程
                callProcessToVoid(id);

            } catch (Exception e) {
                String funNumber = (String) map.get("txtfuncode");
                String rpstandardNumber = (String) map.get("rpstandardcode");

                log.info("基础表-人员信息基础操作失败 funNumber={},rpstandardNumber={}", funNumber,rpstandardNumber);
                log.info(e.getMessage(), e);
            }

        }
    }



    /**
     *  调用存储过程
     *  ------错失标准
     CREATE  PROC  SyncRPStandard

     @companyfid   nvarchar(100),  ----申请公司FID，传空
     @funcode   nvarchar(100),  ----职能代码
     @Serial    nvarchar(100),  ----序号
     @ItemCode   nvarchar(100),  ----错失代码
     @Item    nvarchar(200),  ----错失项
     @Desc    nvarchar(500),  ----说明
     @Lvl    nvarchar(20),   ----等级    '1'  Ⅰ     '2'  Ⅱ    '3' Ⅲ     '4'  \
     @RFCode    nvarchar(100),  ----相关档案代码
     @RFName    nvarchar(100),  ----相关档案名称
     @Auditor   nvarchar(100)   ----审批人   02.0100 张三
     * @param bizId
     */
    private void callProcess(String bizId){

        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.RPStandardBase);
        StringBuilder sql = new StringBuilder("SELECT funcode,serial,rpstandardcode,shuoming,rpstandardname,relevantfilecode,relevantfile ,auditer from ")
                .append(tableName).append(" where id ='")
                //.append("' and oneLevelCode='").append(oneLevelCode)
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());

        log.info("入参map={}",map);

        //调用存储过程
        String RelevanceCompany = "";
        String txtfuncode = MapUtils.getString(map,"funcode","");
        String serial = MapUtils.getString(map,"serial","");
        String rpstandardcode = MapUtils.getString(map,"rpstandardcode","");
        String rpstandard = MapUtils.getString(map,"rpstandardname","");

        String desc = MapUtils.getString(map,"shuoming","");
        String rplevel = "buyongle";


        String relevantfilecode = MapUtils.getString(map,"relevantfilecode","");
        String relevantfile = MapUtils.getString(map,"relevantfile","");
        String auditer = MapUtils.getString(map,"auditer","");
//        String auditer ="";

//        Assert.isFalse(StringUtils.isEmpty(RelevanceCompany),"{}不能为空","RelevanceCompany");
////        Assert.isFalse(firstDept==null ,"{}不能为空","firstDept");
//        Assert.isFalse(StringUtils.isEmpty(txtfuncode),"{}不能为空","txtfuncode");
//        Assert.isFalse(StringUtils.isEmpty(serial),"{}不能为空","serial");
//        Assert.isFalse(StringUtils.isEmpty(rpstandardcode),"{}不能为空","rpstandardcode");
//        Assert.isFalse(StringUtils.isEmpty(rpstandard),"{}不能为空","rpstandard");
//        Assert.isFalse(StringUtils.isEmpty(desc),"{}不能为空","desc");
//        Assert.isFalse(StringUtils.isEmpty(rplevel),"{}不能为空","rplevel");
//        Assert.isFalse(StringUtils.isEmpty(relevantfilecode),"{}不能为空","relevantfilecode");
//        Assert.isFalse(StringUtils.isEmpty(relevantfile),"{}不能为空","relevantfile");
//        Assert.isFalse(StringUtils.isEmpty(auditer),"{}不能为空","auditer");


        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncRPStandard   '%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'",
                RelevanceCompany,txtfuncode,serial,rpstandardcode,rpstandard,desc,rplevel,relevantfilecode,relevantfile,auditer);

        log.info("\n==========准备调用存储过程:{}",execSql);

        sqlService.execute(CloudSqlService.htEas,execSql);

        log.info("\n=============存储过程执行完成");

    }

    /**
     *  调用作废存储过程
     错失标准作废
     CREATE  PROC  RPStandardDisable
     @ItemCode nvarchar(100)   ----问题项代码
     * @param bizId
     */
    private void callProcessToVoid(String bizId){

        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.RPStandardBase);
        StringBuilder sql = new StringBuilder("SELECT rpstandardcode from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());

        log.info("入参map={}",map);

        //调用存储过程

        String rpstandardcode = MapUtils.getString(map,"rpstandardcode","");
        //String personNumber = MapUtils.getString(map,"personNumber","");

        Assert.isFalse(StringUtils.isEmpty(rpstandardcode),"{}不能为空","rpstandardcode");
        //Assert.isFalse(StringUtils.isEmpty(personNumber),"{}不能为空","personNumber");


        String execSql = String.format("exec [HG_LINK].[hg].[dbo].RPStandardDisable    '%s'",
                rpstandardcode );

        log.info("\n==========准备调用作废存储过程:{}",execSql);

        sqlService.execute(CloudSqlService.htEas,execSql);

        log.info("\n=============作废存储过程执行完成");

    }

    /**
     *  查询审批人,返回  员工号+姓名
     * @param bizObject
     * @return
     */
    private String getFileBaseInfoWorkFlowApproval(BizObjectCreatedModel bizObject) {


        WorkflowInstanceModel instanceModel = getWorkflowInstanceFacade().getByObjectId(bizObject.getId());
        List<WorkItemModel> workItems = getWorkflowInstanceFacade().getWorkItems(instanceModel.getId(), true);
        final String finalActivityCode = "Activity17";
        Optional<WorkItemModel> first = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode)).findFirst();
        String participant = null;
        if (first.isPresent()) {
            WorkItemModel workItemModel = first.get();
            participant = workItemModel.getParticipant();
        }

        if (participant == null) {
            participant = bizObject.getCreater().getId();
        }

        UserModel user = getOrganizationFacade().getUser(participant);


        return new StringBuilder(user.getEmployeeNo()).append("　").append(user.getName()).toString();
    }



    /**
     * 判断是否已存在
     * @return
     */
    private String existsBizObject(Map data){

        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.RPStandardBase);
        String rpstandardcode = (String) data.get("rpstandardcode");
       // String personNumber = (String) data.get("personNumber");

        StringBuilder sql = new StringBuilder("select id  from ").append(tableName)
                .append(" where rpstandardcode='").append(rpstandardcode)
                //.append("' and personNumber='").append(personNumber)
                .append("';");

        Map<String, Object> map = sqlService.getMap(sql.toString());

        return (String) map.get("id");
    }

    /**
     *  转换成  基础表-错失标准 的数据
     * @param map
     * @param auditDate
     * @return
     */
    private Map<String,Object> fileInfoBaseMap(Map<String,Object> map,String auditDate,String auditer){
        Map<String, Object> data = new HashMap<>();

        //公司
//        data.put("companyNumber",map.get("companyNumber"));
        //关联单选职能
        data.put("funid",map.get("functionId"));
        //职能代码
        data.put("funcode",map.get("txtfuncode"));
        //序列号
        data.put("serial",map.get("serial"));
        //问题项代码
        data.put("rpstandardcode",map.get("rpstandardcode"));
        //问题项
        data.put("rpstandardname",map.get("rpstandard"));
        //说明
        data.put("desc",map.get("desc"));
        data.put("shuoming",map.get("shuoming"));
        //等级
//        data.put("rplevel",map.get("rplevel"));
        //相关档案代码
        data.put("relevantfilecode",map.get("relevantfilecode"));
        //相关档案
        data.put("relevantfile",map.get("relevantfile"));



        //审批时间
        data.put("auditDate",auditDate);
        //审批人
        data.put("auditer",auditer);

        return data;
    }
}
